export default defineNuxtRouteMiddleware(async (to) => {
  console.log(`[middleware:auth] to.path='${to.path}'`)

  // skip middleware on server
  if (import.meta.server) return

  const { login } = useLogin()
  if (login.value.isLoggedIn) return

  const directus = useDirectus()
  try {
    await directus.refresh()
    login.value.isLoggedIn = true
  }
  catch {
    const redirect = encodeURIComponent(to.path)
    return navigateTo(`/login?redirect=${redirect}`)
  }
})
